package org.example.java_chatroom.api;




import org.example.java_chatroom.model.User;
import org.example.java_chatroom.model.UserMapper;
import org.example.java_chatroom.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author @fiber-cloud
 * @Date 2025/11/3 8:16
 *用户管理相关操作
 */
@RestController
public class UserAPI {
    //加上这个注解是为了直接给接口创建一个实例
    @Resource
    UserMapper userMapper;

    //实现登录方法
    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest req){
        // 创建响应对象，提供更详细的错误信息
        Map<String, Object> response = new HashMap<>();

        try {
            // 1. 验证用户名和密码是否为空
            if (username == null || username.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "用户名不能为空");
                return response;
            }

            if (password == null || password.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "密码不能为空");
                return response;
            }

            // 2. 验证密码长度
            if (password.length() < 6) {
                response.put("success", false);
                response.put("message", "密码长度至少大于6个字符");
                return response;
            }

            // 3. 查询数据库验证用户
            User user = userMapper.selectByName(username);
            if (user == null) {
                response.put("success", false);
                response.put("message", "用户名不存在");
                System.out.println("登录失败! 用户名不存在: " + username);
                return response;
            }

            if (!user.getPassword().equals(password)) {
                response.put("success", false);
                response.put("message", "密码错误");
                System.out.println("登录失败! 密码错误，用户名: " + username);
                return response;
            }

            // 4. 登录成功，创建会话
            System.out.println("登录成功，用户: " + username);
            HttpSession session = req.getSession(true);
            session.setAttribute("user", user);

            // 返回用户信息（不包含密码）
            user.setPassword("");
            response.put("success", true);
            response.put("message", "登录成功");
            response.put("user", user);

        } catch (Exception e) {
            // 处理异常情况
            response.put("success", false);
            response.put("message", "登录失败，系统错误");
            System.out.println("登录异常: " + e.getMessage());
            e.printStackTrace();
        }

        return response;
    }

//    //实现注册方法
//    @PostMapping("/register")
//    @ResponseBody
//    public Object register(String username,String password){
//
//        User user = null;
//        try {
//            user = new User();
//            user.setUsername(username);
//            user.setPassword(password);
//            int ret = userMapper.insert(user);
//            System.out.println("注册 ret："+ ret);
//            user.setPassword("");
//
//        } catch (DuplicateKeyException e) {
//            // 如果insert方法抛出异常，说明用户名重复
//            // 而如果用户名重复，就会注册失败，返回一个空白对象
//            user = new User();
//            System.out.println("注册失败!username = "+username);
//        }
//
//        return user;
//    }

    //实现注册方法 升级版 需要两次输入密码一致才能正确注册
    @PostMapping("/register")
    @ResponseBody

    public Object register(String username, String password, String confirmPassword,
                           String securityQuestion, String securityAnswer) {

        Map<String, Object> res = new HashMap<>();

        try {
            //检查两次密码是否一致
            if (!password.equals(confirmPassword)){
                res.put("success",false);
                res.put("message","两次输入的密码不一致");
                return res;
            }
            //检查密码长度是否符合要求
            if (password.length() < 6){
                res.put("success",false);
                res.put("message","密码长度至少为6字符");
                return res;
            }

            //检查密保问题是否为空
            if (securityQuestion == null || securityQuestion.trim().isEmpty()) {
                res.put("success",false);
                res.put("message","请选择密保问题");
                return res;
            }

            //检查密保答案是否为空
            if (securityAnswer == null || securityAnswer.trim().isEmpty()) {
                res.put("success",false);
                res.put("message","密保答案不能为空");
                return res;
            }

            //创建用户并保存
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setSecurityQuestion(securityQuestion);
            user.setSecurityAnswer(securityAnswer);

            int ret = userMapper.insert(user);

            System.out.println("注册 ret: "+ret);

            //返回成功响应
            if (ret > 0 ){
                res.put("success",true);
                res.put("message","注册成功");
                res.put("userId",user.getUserId());

                //处理一下密码
                user.setPassword("");
                res.put("user",user);
            }else {
                res.put("success", false);
                res.put("message", "注册失败，请稍后重试");
            }
        }catch (DuplicateKeyException e){
            // 处理用户名重复的情况
            res.put("success", false);
            res.put("message", "用户名已存在");
            System.out.println("注册失败! 用户名重复 username = " + username);
        }catch (Exception e){
            // 处理其他异常
            res.put("success", false);
            res.put("message", "注册失败，系统错误");
            System.out.println("注册异常: " + e.getMessage());
            e.printStackTrace();
        }
        return res;
    }


    //获取到当前的登录信息
    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest req){
        //1.先从请求中获取到会话
        HttpSession session = req.getSession(false);
        if (session == null){
            //当前会话不存在——用户没登录
            System.out.println("[getUserInfo] 当前获取不到session对象！");
            return new User();
        }
        // 2.从会话中获取到之前保存的用户对象
        User user = (User) session.getAttribute("user");
        if (user == null){
            System.out.println("[getUserInfo] 当前获取不到user对象！");
            return new User();
        }
        user.setPassword("");
        return user;
    }

    @Autowired
    private UserService userService;

    /**
     * 获取密保问题
     */
    @PostMapping("/security-question")
    public Map<String, Object> getSecurityQuestion(@RequestBody Map<String, String> request) {
        String username = request.get("username");

        if (username == null || username.trim().isEmpty()) {
            return createErrorResponse("用户名不能为空");
        }

        return userService.getSecurityQuestion(username);
    }

    /**
     * 通过密保问题重置密码
     */
    @PostMapping("/reset-password-by-security")
    public Map<String, Object> resetPasswordBySecurity(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        String securityAnswer = request.get("securityAnswer");
        String newPassword = request.get("newPassword");
        String confirmPassword = request.get("confirmPassword");

        // 参数验证
        if (username == null || username.trim().isEmpty()) {
            return createErrorResponse("用户名不能为空");
        }

        if (securityAnswer == null || securityAnswer.trim().isEmpty()) {
            return createErrorResponse("密保答案不能为空");
        }

        if (newPassword == null || newPassword.trim().isEmpty()) {
            return createErrorResponse("新密码不能为空");
        }

        if (confirmPassword == null || confirmPassword.trim().isEmpty()) {
            return createErrorResponse("确认密码不能为空");
        }

        return userService.resetPasswordBySecurityQuestion(username, securityAnswer, newPassword, confirmPassword);
    }

    /**
     * 设置密保问题
     */
    @PostMapping("/set-security-question")
    public Map<String, Object> setSecurityQuestion(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        String securityQuestion = request.get("securityQuestion");
        String securityAnswer = request.get("securityAnswer");

        if (username == null || username.trim().isEmpty()) {
            return createErrorResponse("用户名不能为空");
        }

        if (securityQuestion == null || securityQuestion.trim().isEmpty()) {
            return createErrorResponse("密保问题不能为空");
        }

        if (securityAnswer == null || securityAnswer.trim().isEmpty()) {
            return createErrorResponse("密保答案不能为空");
        }

        return userService.setSecurityQuestion(username, securityQuestion, securityAnswer);
    }

    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        return response;
    }

}
